﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace Ue.Extensions
{
    public static class TypeExtensions
    {
        /// <summary>
        /// 取得type标有IAttribute类型Attribute的属性集合
        /// </summary>
        /// <typeparam name="IAttribute"></typeparam>
        /// <param name="col"></param>
        /// <returns></returns>
        public static IDictionary<PropertyInfo, IList<IAttribute>> GetProperties<IAttribute>(this Type col)
            where IAttribute : Attribute
        {
            IDictionary<PropertyInfo, IList<IAttribute>> directory = new Dictionary<PropertyInfo, IList<IAttribute>>();

            PropertyInfo[] properties = col.GetProperties(
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);

            foreach (PropertyInfo property in properties)
            {
                var attributes = property.GetCustomAttributes(typeof(IAttribute), true);

                if (attributes.Length > 0)
                {
                    directory.Add(
                        property,
                        new List<IAttribute>(attributes.Cast<IAttribute>()));
                }
            }

            return directory;
        }
    }
}
